# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '710141': {  # dwc 支付宝H5、微信2.9%（20---20000）
        'API_KEY': '2301fd81ebd6b03d8358e529bfee13ff',
        'gateway': 'http://www.hpay99.com/api/v1/createorder',
        # 'query_gateway': 'http://www.hpay99.com/api/v1/paymentresult',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# 0支付宝直充 1支付宝扫码充值 2微信扫码 3同时支持微信跟支付宝扫码充值。
def _get_pay_type(service):
    if service == 'alipay':
        return '0'
    elif service == 'alipay_scan':
        return '1'
    elif service == 'wechat_scan':
        return '2'
    elif service == 'all_scan':
        return '3'
    else:
        return '0'


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return ''


def generate_sign(s):
    '''  生成下单签名 '''
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_sign(params, sign):
    calculated_sign = generate_sign(params)
    if sign != calculated_sign:
        _LOGGER.info("hpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "<input type='submit' style='display:none;'></form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


def _build_head(d):
    html = '<head><Version>{}</Version><MerCode>{}</MerCode><Signature>{}</Signature></head>'.format(
        d['Version'], d['MerCode'], d['Signature']
    )
    return html


def _build_body(d):
    html = '<body><MerBillNo>{}</MerBillNo><NotifyUrl><![CDATA[{}]]></NotifyUrl><FailUrl><![CDATA[{}]]></FailUrl>' \
           '<ReturnUrl><![CDATA[{}]]></ReturnUrl><PayType>{}</PayType><Amount>{}</Amount><GoodsName>{' \
           '}</GoodsName></body>'.format(
        d['MerBillNo'], d['NotifyUrl'], d['FailUrl'], d['ReturnUrl'], d['PayType'], d['Amount'], d['GoodsName']
    )
    return html


def _build_para(d):
    html = '<HPay><GateWayReq>{}{}</GateWayReq></HPay>'.format(
        d['head'], d['body']
    )
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_bodys = OrderedDict((
        ('MerBillNo', str(pay.id)),
        ('NotifyUrl', '{}/pay/api/{}/hpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('FailUrl', '{}/pay/api/{}/hpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('ReturnUrl', '{}/pay/api/{}/hpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('PayType', _get_pay_type(service)),
        ('Amount', '%.2f' % pay_amount),
        ('GoodsName', 'hpay_charge'),
    ))
    s = _build_body(parameter_bodys) + app_id + api_key
    Signature = generate_sign(s)
    parameter_headers = {'Version': 'v1.0.0', 'MerCode': app_id, 'Signature': Signature}
    paras_head_and_body = {'head': _build_head(parameter_headers), 'body': _build_body(parameter_bodys)}
    paras_create = {'pGateWayReq': _build_para(paras_head_and_body)}
    _LOGGER.info("hpay create: %s", paras_create)
    html_text = _build_form(paras_create, _get_gateway(app_id))
    _LOGGER.info("hpay html_text: %s", html_text)
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('hpay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    pay_id = _get_str(data['PaymentResult'], '<MerBillNo>', '</MerBillNo>')
    api_key = _get_api_key(app_id)
    _LOGGER.info("hpay notify data: %s, order_id is: %s", data, pay_id)
    signature = _get_str(data['PaymentResult'], '<Signature>', '</Signature>')
    body = _get_str(data['PaymentResult'], '</head>', '</GateWayRsp>')
    s = body + app_id + api_key
    verify_sign(s, signature)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('hpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = _get_str(data['PaymentResult'], '<Status>', '</Status>')
    trade_no = _get_str(data['PaymentResult'], '<OrderId>', '</OrderId>')
    total_fee = float(_get_str(data['PaymentResult'], '<Amount>', '</Amount>'))
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)
    #  Y#交易成功; N#交易失败; P#交易处理中
    if trade_status == 'Y':
        _LOGGER.info('hpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
